package stub

import (
	"sync"
	"sync/atomic"
)

var (
	once         sync.Once
	clientStubID uint32
)

type ClientStubMgr struct {
	clientStubs map[uint32]*ClientStub
	register    map[uint64]bool
}

func init() {
	once.Do(func() {
		clientStubID = 1
	})
}

func NewClientStubMgr() *ClientStubMgr {
	return &ClientStubMgr{
		clientStubs: make(map[uint32]*ClientStub),
	}
}

func (cb *ClientStubMgr) GetClientStub(stubId uint32) *ClientStub {
	v, ok := cb.clientStubs[stubId]
	if !ok {
		return nil
	}
	return v
}

func (cb *ClientStubMgr) AddClientStub(cstub *ClientStub) bool {
	if cstub == nil {
		return false
	}

	cstub.stubID = atomic.AddUint32(&clientStubID, 1)
	if _, ok := cb.clientStubs[cstub.stubID]; ok {
		//删除 旧的重复的stub
		//TODO 添加日志
		delete(cb.clientStubs, cstub.stubID)
	}
	cb.clientStubs[cstub.stubID] = cstub
	return true
}
